﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Controls;
using VAdvantage.Classes;
using VAdvantage.Utility;
using VAdvantage.Logging;
using VAdvantage.Model;
using VAdvantage.DataBase;
using System.ComponentModel;
using System.Threading;

namespace VAdvantage.Apps.AForms
{
    public partial class VBOMDrop : UserControl, FormPanel
    {
        #region Private Variables
        //	Window No				
        private int _windowNo = 0;
        //	FormFrame					
        private FormFrame _frame;
        //	Product to create BOMs from	
        private MProduct _product;
        // BOM Qty						
        private Decimal _qty = Envs.ONE;
        //	Line Counter				
        private int _bomLine = 0;
        //Logger			
        private static VLogger log = VLogger.GetVLogger(typeof(VBOMDrop).FullName);

        //	List of all selectors		
        //private List<JToggleButton> _selectionList = new List<JToggleButton>();
        private List<Control> _selectionList = new List<Control>();
        //	List of all quantities		
        private List<VNumTextBox> _qtyList = new List<VNumTextBox>();
        //	List of all products		
        private List<int> _productList = new List<int>();
        // Alternative Group Lists
        //private HashMap<String, ButtonGroup> _buttonGroups = new HashMap<String, ButtonGroup>();
        private Dictionary<String, RadioButton> _buttonGroups = new Dictionary<string, RadioButton>();
        private static int WINDOW_WIDTH = 600;	//	width of the window
        //
        //private VNumber txtProductQty = new VNumber("Qty", true, false, true, DisplayType.Quantity, Msg.translate(Envs.getCtx(), "Qty"));
        private VNumTextBox txtProductQty = new VNumTextBox("Qty", true, false, true, DisplayType.Quantity, Msg.Translate(Envs.GetContext(), "Qty"));

        private SLControls.Controls.VComboBox vcmbOrderField = null;
        private SLControls.Controls.VComboBox vcmbProductField = null;
        private SLControls.Controls.VComboBox vcmbInvoiceField = null;
        private SLControls.Controls.VComboBox vcmbProjectField = null;

        #endregion


        public VBOMDrop()
        {
            InitializeComponent();
        }

        public void Init(int WindowNo, FormFrame frame)
        {

            InitializeComponent();
            //Quantity Text Box
            this.txtProductQty.HorizontalAlignment = HorizontalAlignment.Stretch;
            // this.txtProductQty.Location = new System.Drawing.Point(393, 4);
            this.txtProductQty.Name = "txtProductQty";
            //this.txtProductQty.Size = new System.Drawing.Size(205, 20);
            this.txtProductQty.TabIndex = 0;
            this.vdgvSelect.Children.Add(this.txtProductQty);
            Grid.SetColumn(txtProductQty, 4);
            Grid.SetRow(txtProductQty, 2);

            _windowNo = WindowNo;
            _frame = frame;
            _frame.Height = App.Current.Host.Content.ActualHeight - 25;
            _frame.Width = App.Current.Host.Content.ActualWidth;

            Envs.GetCtx().SetIsSOTrx(_windowNo, true);
            //GetLookUp();
            this.Visibility = System.Windows.Visibility.Visible;
            _frame.ContentGrid.Children.Add(this);
            LayoutRoot.Background = new SolidColorBrush(DataBase.GlobalVariable.WINDOW_BACK_COLOR);
            this.txtProductQty.FireTextChanged += new EventHandler(txtProductQty_FireTextChanged);
          SetBusy(true);
            try
            {
                //	Top Selection Panel
                //CreateSelectionPanel(true, true, true);
                ComboLayOut();
                GetData();
                CreateMainPanel();
                //_frame.GetContentPane().Controls.Add((Control)this);
            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, "", e);
            }
            //Haldel Form size
            SizeIt();
            // this.txtProductQty.FireTextChanged += new System.EventHandler(this.txtProductQty_TextChanged);
        }


        private void SetBusy(bool value)
        {

            this.IsEnabled = !value;
            busyWindow.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            txtBusy.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
        }

        void txtProductQty_FireTextChanged(object sender, EventArgs e)
        {
            _qty = Util.GetValueOfDecimal(txtProductQty.Text);
            if (Util.GetValueOfInt(vcmbProductField.Items.Count) > 0)
            {
                KeyNamePair pp = (KeyNamePair)vcmbProductField.SelectedItem;
                _product = MProduct.Get(Envs.GetContext(), pp.GetKey());
            }

            CreateMainPanel();
            SizeIt();
            OkCheck();
        }

        /// <summary>
        /// Dynamic Display of Select Group box
        /// </summary>
        private void ComboLayOut()
        {
            // 
            // vcmbOrderField
            // 

            //this.vcmbOrderField.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
            vcmbOrderField = new SLControls.Controls.VComboBox();
            this.vcmbOrderField.HorizontalAlignment = HorizontalAlignment.Stretch;
            this.vcmbOrderField.Height = 20;
            this.vcmbOrderField.Margin = new Thickness(0, 5, 5, 0);
            this.vcmbOrderField.Name = "vcmbOrderField";
            
            this.vcmbOrderField.TabIndex = 9;
            this.vcmbOrderField.SelectionChanged += new SelectionChangedEventHandler(vcmbOrderField_SelectionChanged);
            this.vdgvSelect.Children.Add(vcmbOrderField);
            Grid.SetRow(vcmbOrderField, 1);
            Grid.SetColumn(vcmbOrderField, 2);


            // 
            // vcmbProductField
            // 
            //this.vcmbProductField.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
            vcmbProductField = new SLControls.Controls.VComboBox();
            this.vcmbProductField.HorizontalAlignment = HorizontalAlignment.Stretch;
            this.vcmbProductField.Height = 20;
            this.vcmbProductField.Margin = new Thickness(0,5, 5, 0);
            this.vcmbProductField.Name = "vcmbProductField";
            //this.vcmbProductField.Size = new System.Drawing.Size(204, 21);
            this.vcmbProductField.TabIndex = 5;
            this.vcmbProductField.SelectionChanged += new SelectionChangedEventHandler(vcmbProductField_SelectionChanged);
            this.vdgvSelect.Children.Add(vcmbProductField);
            Grid.SetColumn(vcmbProductField, 2);
            Grid.SetRow(vcmbProductField, 0);

            // 
            // vcmbInvoiceField
            // 
            //this.vcmbInvoiceField.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
            vcmbInvoiceField = new SLControls.Controls.VComboBox();
            vcmbInvoiceField.Height = 20;
            this.vcmbInvoiceField.HorizontalAlignment = HorizontalAlignment.Stretch;
            this.vcmbInvoiceField.Margin = new Thickness(0, 5, 5, 0);
            this.vcmbInvoiceField.Name = "vcmbInvoiceField";
            // this.vcmbInvoiceField.Size = new System.Drawing.Size(204, 21);
            this.vcmbInvoiceField.TabIndex = 10;
            this.vcmbInvoiceField.SelectionChanged += new SelectionChangedEventHandler(vcmbInvoiceField_SelectionChanged);
            this.vdgvSelect.Children.Add(this.vcmbInvoiceField);
            Grid.SetColumn(vcmbInvoiceField, 4);
            Grid.SetRow(vcmbInvoiceField, 0);

            // 
            // vcmbProjectField
            // this.vcmbProjectField.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
            vcmbProjectField = new SLControls.Controls.VComboBox();
            this.vcmbProjectField.Height = 20;
            this.vcmbProjectField.HorizontalAlignment = HorizontalAlignment.Stretch;
            this.vcmbProjectField.Margin = new Thickness(0, 5, 5, 0);
            this.vcmbProjectField.Name = "vcmbProjectField";
            //this.vcmbProjectField.Size = new System.Drawing.Size(204, 21);
            this.vcmbProjectField.TabIndex = 11;
            this.vcmbProjectField.SelectionChanged += new SelectionChangedEventHandler(vcmbProjectField_SelectionChanged);
            this.vdgvSelect.Children.Add(this.vcmbProjectField);
            Grid.SetColumn(vcmbProjectField, 4);
            Grid.SetRow(vcmbProjectField, 1);
        }

        /// <summary>
        /// Size Window
        /// </summary>
        private void SizeIt()
        {
            //	Frame
            //            Size size = _frame.Size;
            Size size = _frame.RenderSize;
            size.Width = WINDOW_WIDTH;
            //_frame.setSize(size);
            if (vcmbProductField == null || vcmbProductField.SelectedIndex == -1 || vcmbProductField.SelectedIndex == 0)
            {
                _frame.Height = 280;
            }
            else
            {
                _frame.Height = 280 /*+ groupBox2.PreferredSize.Height*/ + vdgvProduct.Height;
            }
        }

        /// <summary>
        /// Dispose
        /// </summary>
        public void Dispose()
        {
            if (_frame != null)
            {
                _frame.Dispose();
            }
            _frame = null;
            //removeAll();
            //if (selectionPanel != null)
            //{
            //    selectionPanel.removeAll();
            //}
            // selectionPanel = null;
            if (_selectionList != null)
            {
                _selectionList.Clear();
            }
            _selectionList = null;
            if (_productList != null)
            {
                _productList.Clear();
            }
            _productList = null;
            if (_qtyList != null)
            {
                _qtyList.Clear();
            }
            _qtyList = null;
            if (_buttonGroups != null)
            {
                // _buttonGroups.clear();
            }
            _buttonGroups = null;
        }


        public void GetData()
        {
            SetBusy(true);
            txtBusy.Text = Msg.GetMsg("Processing");
            KeyNamePair[] getProduct = null;
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                String sql = "SELECT M_Product_ID, Name "
                    + "FROM M_Product "
                    + "WHERE IsBOM='Y' AND IsVerified='Y' AND IsActive='Y' "
                    + "ORDER BY Name";
                getProduct = DB.GetKeyNamePairs(MRole.GetDefault().AddAccessSQL(
                    sql, "M_Product", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO), true);



                KeyNamePair[] getOrder = null;

                sql = "SELECT C_Order_ID, DocumentNo || '_' || GrandTotal "
                     + "FROM C_Order "
                     + "WHERE Processed='N' AND DocStatus='DR' "
                     + "ORDER BY DocumentNo";
                getOrder = DB.GetKeyNamePairs(MRole.GetDefault().AddAccessSQL(
                    sql, "C_Order", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO), true);




                KeyNamePair[] getProject = null;

                sql = "SELECT C_Project_ID, Name "
                    + "FROM C_Project "
                    + "WHERE Processed='N' AND IsSummary='N' AND IsActive='Y'"
                    + " AND ProjectCategory<>'S' "
                    + "ORDER BY Name";
                getProject = DB.GetKeyNamePairs(MRole.GetDefault().AddAccessSQL(
                    sql, "C_Project", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO), true);


                KeyNamePair[] getInvoice = null;

                sql = "SELECT C_Invoice_ID, DocumentNo || '_' || GrandTotal "
                       + "FROM C_Invoice "
                       + "WHERE Processed='N' AND DocStatus='DR' "
                       + "ORDER BY DocumentNo";
                getInvoice = DB.GetKeyNamePairs(MRole.GetDefault().AddAccessSQL(
                    sql, "C_Invoice", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO), true);


                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => CreateSelectionPanel(true, true, true, getProduct, getOrder, getProject, getInvoice));
            });
        }




        /// <summary>
        /// Create Selection Panel
        /// </summary>
        /// <param name="order"></param>
        /// <param name="invoice"></param>
        /// <param name="project"></param>
        private void CreateSelectionPanel(bool order, bool invoice, bool project, KeyNamePair[] getProduct, KeyNamePair[] getOrder, KeyNamePair[] getProject, KeyNamePair[] getInvoice)
        {
            int row = 0;
            Object[] value;
            //selectionPanel.setBorder(new TitledBorder(Msg.translate(Envs.getCtx(), "Selection")));
            //  Textbox1.Text = Msg.Translate(Envs.GetContext(), "Selection");
            // vcmbProductField = new SLControls.Controls.VComboBox();//(GetProducts());
            value = getProduct;
            for (int i = 0; i < value.Length; i++)
            {
                vcmbProductField.Items.Add(value[i]);
            }
            value = null;
            vlblProduct.Content = Msg.Translate(Envs.GetContext(), "M_Product_ID");
            //label.setLabelFor(cmbProductField);
            //selectionPanel.add(label, new ALayoutConstraint(row++, 0));
            //selectionPanel.add(cmbProductField);
            //cmbProductField.addActionListener(this);

            //	Qty
            vlblQuantity.Content = Msg.Translate(Envs.GetContext(), "Qty");
            //label.setLabelFor(txtProductQty);
            //selectionPanel.add(label);
            //selectionPanel.add(txtProductQty);
            txtProductQty.Text = "1";// Envs.ONE.ToString();
            txtProductQty.Height = 20;
            txtProductQty.Margin = new Thickness(0, 5, 5, 0);

            if (order)
            {
                //vcmbOrderField = new SLControls.Controls.VComboBox();//(GetOrders());
                value = getOrder;
                for (int i = 0; i < value.Length; i++)
                {
                    vcmbOrderField.Items.Add(value[i]);
                }
                value = null;
                vlblOrder.Content = Msg.Translate(Envs.GetContext(), "C_Order_ID");
                //label.setLabelFor(cmbOrderField);
                //selectionPanel.add(label, new ALayoutConstraint(row++, 0));
                //selectionPanel.add(cmbOrderField);
                //cmbOrderField.addActionListener(this);
            }
            if (invoice)
            {
                // vcmbInvoiceField = new SLControls.Controls.VComboBox();//(GetInvoices());
                value = getInvoice;
                for (int i = 0; i < value.Length; i++)
                {
                    vcmbInvoiceField.Items.Add(value[i]);
                }
                value = null;
                vlblInvoice.Content = Msg.Translate(Envs.GetContext(), "C_Invoice_ID");
                //label.setLabelFor(cmbInvoiceField);
                //selectionPanel.add(label, new ALayoutConstraint(row++, 0));
                //selectionPanel.add(cmbInvoiceField);
                //cmbInvoiceField.addActionListener(this);
            }
            if (project)
            {
                // vcmbProjectField = new SLControls.Controls.VComboBox();//(GetProjects());
                value = getProject;
                for (int i = 0; i < value.Length; i++)
                {
                    vcmbProjectField.Items.Add(value[i]);
                }
                value = null;
                vlblProject.Content = Msg.Translate(Envs.GetContext(), "C_Project_ID");
                //label.setLabelFor(cmbProjectField);
                //selectionPanel.add(label, new ALayoutConstraint(row++, 0));
                //selectionPanel.add(cmbProjectField);
                //cmbProjectField.addActionListener(this);
            }
            //	Enabled in ActionPerformed
            //confirmPanel.getOKButton().setEnabled(false);
            vbtnOk.IsEnabled = false;
            SetBusy(false);
        }



        ///////// <summary>
        ///////// Get Array of BOM Products
        ///////// </summary>
        ///////// <returns>products</returns>
        //////private KeyNamePair[] GetProducts()
        //////{
        //////    KeyNamePair[] getProduct = null;
        //////    System.Threading.ThreadPool.QueueUserWorkItem(delegate
        //////    {
        //////        String sql = "SELECT M_Product_ID, Name "
        //////            + "FROM M_Product "
        //////            + "WHERE IsBOM='Y' AND IsVerified='Y' AND IsActive='Y' "
        //////            + "ORDER BY Name";
        //////        getProduct = DB.GetKeyNamePairs(MRole.GetDefault().AddAccessSQL(
        //////            sql, "M_Product", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO), true);
        //////    });
        //////    return getProduct;
        //////}

        ///////// <summary>
        ///////// Get Array of open Orders
        ///////// </summary>
        ///////// <returns>orders</returns>
        //////private KeyNamePair[] GetOrders()
        //////{
        //////    KeyNamePair[] getOrder = null;
        //////    System.Threading.ThreadPool.QueueUserWorkItem(delegate
        //////    {
        //////        String sql = "SELECT C_Order_ID, DocumentNo || '_' || GrandTotal "
        //////            + "FROM C_Order "
        //////            + "WHERE Processed='N' AND DocStatus='DR' "
        //////            + "ORDER BY DocumentNo";
        //////        getOrder = DB.GetKeyNamePairs(MRole.GetDefault().AddAccessSQL(
        //////            sql, "C_Order", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO), true);
        //////    });
        //////    return getOrder;
        //////}

        ///////// <summary>
        ///////// Get Array of open non service Projects
        ///////// </summary>
        ///////// <returns>orders</returns>
        //////private KeyNamePair[] GetProjects()
        //////{
        //////    KeyNamePair[] getProject = null;
        //////    System.Threading.ThreadPool.QueueUserWorkItem(delegate
        //////    {
        //////        String sql = "SELECT C_Project_ID, Name "
        //////            + "FROM C_Project "
        //////            + "WHERE Processed='N' AND IsSummary='N' AND IsActive='Y'"
        //////            + " AND ProjectCategory<>'S' "
        //////            + "ORDER BY Name";
        //////        getProject = DB.GetKeyNamePairs(MRole.GetDefault().AddAccessSQL(
        //////            sql, "C_Project", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO), true);
        //////    });
        //////    return getProject;
        //////}

        ///////// <summary>
        ///////// Get Array of open Invoices
        ///////// </summary>
        ///////// <returns>invoices</returns>
        //////private KeyNamePair[] GetInvoices()
        //////{
        //////    KeyNamePair[] getInvoice = null;
        //////    System.Threading.ThreadPool.QueueUserWorkItem(delegate
        //////    {
        //////        String sql = "SELECT C_Invoice_ID, DocumentNo || '_' || GrandTotal "
        //////            + "FROM C_Invoice "
        //////            + "WHERE Processed='N' AND DocStatus='DR' "
        //////            + "ORDER BY DocumentNo";
        //////        getInvoice= DB.GetKeyNamePairs(MRole.GetDefault().AddAccessSQL(
        //////            sql, "C_Invoice", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO), true);
        //////    });
        //////    return getInvoice;
        //////}

        /// <summary>
        /// Create Main Panel.
        /// Called when changing Product 	
        /// </summary>
        private void CreateMainPanel()
        {

            
            log.Config(": " + _product);
            //this.removeAll();
            vdgvProduct.Children.Clear();

            //this.setPreferredSize(null);
            //tblp2.PreferredSize = new System.Drawing.Size(760, 215);
            //groupBox2.Size.Height = 20;
            //this.Invalidate();

            _selectionList.Clear();
            _productList.Clear();
            _qtyList.Clear();
            // _buttonGroups.clear();
            //
            //this.setLayout(new ALayout());
            String title = Msg.GetMsg(Envs.GetContext(), "SelectProduct");
            if (_product != null && _product.Get_ID() > 0)
            {
                title = _product.GetName();
                if (_product.GetDescription() != null && _product.GetDescription().Length > 0)
                {
                    //this.setToolTipText(_product.getDescription());
                }
                _bomLine = 0;
                BomLines(_product, _qty);
            }
            //  Textbox2.Text = title;
            //tblp2.AutoSize = true;
            //groupBox2.AutoSize = true;
            // _frame.Height = 200;
            //this.setBorder(new TitledBorder(title));
        }

        public void BomLines(MProduct product, Decimal qty)
        {
            MProductBOM[] bomLines = null;
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                bomLines = MProductBOM.GetBOMLines(product);
                for (int i = 0; i < bomLines.Length; i++)
                    AddBOMLine(bomLines[i], qty);
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => AddBOMLines(product, qty, bomLines));

            });
        }

        /// <summary>
        /// Add BOM Lines to this.
        /// Called recursively
        /// </summary>
        /// <param name="product">product</param>
        /// <param name="qty">quantity</param>
        private void AddBOMLines(MProduct product, Decimal qty, MProductBOM[] bomLines)
        {

            //        tblp2.RowCount += 1;
            RowDefinition rowDefinition = new RowDefinition();
            rowDefinition.Height = new GridLength(25);
            vdgvProduct.RowDefinitions.Add(rowDefinition);
            if (bomLines != null)
                log.Fine("#" + bomLines.Length);
           SetBusy(false);
        }

        /// <summary>
        /// Add BOM Line to this.
        /// Calls addBOMLines if added product is a BOM
        /// </summary>
        /// <param name="line">BOM Line</param>
        /// <param name="qty">quantity</param>
        private void AddBOMLine(MProductBOM line, Decimal qty)
        {
           // Envs.SetBusyIndicator(true);
            log.Fine(line.ToString());
            String bomType = line.GetBOMType();
            if (bomType == null)
            {
                bomType = MProductBOM.BOMTYPE_StandardPart;
            }
            //
            Decimal lineQty = Decimal.Multiply(line.GetBOMQty(), qty);
            MProduct product = line.GetProduct();
            if (product == null)
            {
                return;
            }
            if (product.IsBOM() && product.IsVerified())
            {

                BomLines(product, lineQty);

            }
            else
            {
                GetDisplay(line.GetM_Product_ID(),
                    product.GetM_Product_ID(), bomType, product.GetName(), lineQty);
            }

        }

        public void GetDisplay(int parentM_Product_ID, int M_Product_ID, String bomType, String name, Decimal lineQty)
        {
            bool standard = false;
            bool Operational = false;
            if (MProductBOM.BOMTYPE_StandardPart.Equals(bomType))
            {
                standard = true;
            }
            if (MProductBOM.BOMTYPE_OptionalPart.Equals(bomType))
            {
                Operational = true;
            }
            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => AddDisplay(parentM_Product_ID, M_Product_ID, bomType, name, lineQty, standard, Operational));

        }




        /// <summary>
        /// Add Line to Display
        /// </summary>
        /// <param name="parentM_Product_ID">parent product</param>
        /// <param name="M_Product_ID">product</param>
        /// <param name="bomType">bom type</param>
        /// <param name="name">name</param>
        /// <param name="lineQty">qty</param>
        private void AddDisplay(int parentM_Product_ID,
            int M_Product_ID, String bomType, String name, Decimal lineQty, bool standard, bool Operational)
        {
            //this.tblp2.RowCount = _bomLine + 1;

            for (int i = 0; i < _bomLine + 1; i++)
            {
                RowDefinition rowDefinition = new RowDefinition();
                rowDefinition.Height = new GridLength(25);
                vdgvProduct.RowDefinitions.Add(rowDefinition);
            }
            log.Fine("M_Product_ID=" + M_Product_ID + ",Type=" + bomType + ",Name=" + name + ",Qty=" + lineQty);
            //
            bool selected = true;
            if (standard)
            {
                String title = "";
                //JCheckBox cb = new JCheckBox(title);
                CheckBox chkCB = new CheckBox();

                chkCB.Click += new RoutedEventHandler(chkCB_Click);
                chkCB.Content = title;
                chkCB.IsChecked = true;
                chkCB.IsEnabled = false;
                _selectionList.Add(chkCB);
                //this.tblp2.Controls.Add(chkCB, 0, _bomLine);//_bomLine++
                vdgvProduct.Children.Add(chkCB);
                Grid.SetColumn(chkCB, 1);
                Grid.SetRow(chkCB, _bomLine);
                chkCB.HorizontalAlignment = HorizontalAlignment.Right;
                chkCB.Margin = new Thickness(5);

            }
            else if (Operational)
            {
                String title = Msg.GetMsg(Envs.GetContext(), "Optional");
                //JCheckBox cb = new JCheckBox(title);
                CheckBox cb = new CheckBox();
                cb.Click += new RoutedEventHandler(cb_Click);
                cb.Content = title;
                //cb.setSelected(false);
                cb.IsChecked = false;
                selected = false;
                //cb.addActionListener(this);
                _selectionList.Add(cb);
                cb.HorizontalAlignment = HorizontalAlignment.Right;
                //this.tblp2.Controls.Add(cb, 0, _bomLine);
                vdgvProduct.Children.Add(cb);
                Grid.SetColumn(cb, 1);
                Grid.SetRow(cb, _bomLine);
                cb.Margin = new Thickness(5);
            }
            else	//	Alternative
            {
                String title = Msg.GetMsg(Envs.GetContext(), "Alternative") + " " + bomType;
                //JRadioButton b = new JRadioButton(title);
                RadioButton b = new RadioButton();
                b.Click += new RoutedEventHandler(b_Click);
                b.Content = title;
                String groupName = parentM_Product_ID.ToString() + "_" + bomType;
                log.Fine("ButtonGroup=" + groupName);
                b.IsChecked = true;		//	select first one
                b.HorizontalAlignment = HorizontalAlignment.Right;
                _selectionList.Add(b);
                //this.tblp2.Controls.Add(b, 0, _bomLine);
                vdgvProduct.Children.Add(b);
                Grid.SetColumn(b, 1);
                Grid.SetRow(b, _bomLine);
                b.Margin = new Thickness(5);

            }
            //	Add to List & display
            _productList.Add(M_Product_ID);
            VAdvantage.Controls.VNumTextBox txtqty = new VAdvantage.Controls.VNumTextBox("Qty", true, false, true, DisplayType.Quantity, name);
            txtqty.SetValue(lineQty);
            
            //qty.setReadWrite(selected);
            txtqty.IsEnabled = selected;
            _qtyList.Add(txtqty);
            Label label = new Label();
            label.Content = name;
            //label.AutoSize = true;
            label.HorizontalAlignment = HorizontalAlignment.Right;
            txtqty.HorizontalAlignment = HorizontalAlignment.Stretch;
            //this.tblp2.Controls.Add(label, 2, _bomLine);
            //this.tblp2.Controls.Add(txtqty, 3, _bomLine);

            vdgvProduct.Children.Add(label);
            Grid.SetColumn(label, 3);
            Grid.SetRow(label, _bomLine);
            label.Margin = new Thickness(0, 5, 0, 5);
            
            vdgvProduct.Children.Add(txtqty);
            Grid.SetColumn(txtqty, 4);
            Grid.SetRow(txtqty, _bomLine);
            txtqty.Margin = new Thickness(10, 5, 0, 5);
            txtqty.Height = 20;
            ++_bomLine;
           SetBusy(false);
        }


        /// <summary>
        /// Get Preferred Size
        /// </summary>
        /// <returns>size</returns>
        /// public Dimension getPreferredSize()
        public Size GetPreferredSize()
        {
            //Dimension size = super.getPreferredSize();
            //Size size = base.Size;
            Size size = base.RenderSize;
            if (size.Width > WINDOW_WIDTH)
            {
                size.Width = WINDOW_WIDTH - 30;
            }
            return size;
        }

        /// <summary>
        /// check box click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBox_Click(object sender, EventArgs e)
        {
            Cmd_Selection(sender);
        }

        /// <summary>
        /// 	Enable/disable qty based on selection
        /// </summary>
        /// <param name="source">JCheckBox or JRadioButton</param>
        private void Cmd_Selection(object source)
        {
            for (int i = 0; i < _selectionList.Count; i++)
            {
                if (source == _selectionList[i])
                {
                    bool selected = IsSelectionSelected(source);
                    VAdvantage.Controls.VNumTextBox qty = (VAdvantage.Controls.VNumTextBox)_qtyList[i];
                    //qty.setReadWrite(selected);
                    qty.IsEnabled = selected;
                    return;
                }
            }
            log.Log(Level.SEVERE, "not found - " + source);
        }

        /// <summary>
        /// Is Selection Selected
        /// </summary>
        /// <param name="source">CheckBox or RadioButton</param>
        /// <returns>true if selected</returns>
        private bool IsSelectionSelected(Object source)
        {
            bool retValue = false;
           

                if (source is CheckBox)
                {
                    retValue = (bool)((CheckBox)source).IsChecked;
                }
                else if (source is RadioButton)
                {
                    retValue = (bool)((RadioButton)source).IsChecked;
                }
                else
                {
                    log.Log(Level.SEVERE, "Not valid - " + source);
                }
           return retValue;
        }

        /// <summary>
        /// Save Selection
        /// </summary>
        /// <returns>true if saved</returns>
        private bool Cmd_Save(KeyNamePair ppOrder,KeyNamePair ppInvoice,KeyNamePair ppProject)
        {
           // KeyNamePair pp = (KeyNamePair)vcmbOrderField.SelectedItem;
            if (ppOrder != null && ppOrder.GetKey() > 0)
            {
                return Cmd_SaveOrder(ppOrder.GetKey());
            }
            //
           // pp = (KeyNamePair)vcmbInvoiceField.SelectedItem;
            if (ppInvoice != null && ppInvoice.GetKey() > 0)
            {
                return Cmd_SaveInvoice(ppInvoice.GetKey());
            }
            //
           // pp = (KeyNamePair)vcmbProjectField.SelectedItem;
            if (ppProject != null && ppProject.GetKey() > 0)
            {
                return Cmd_SaveProject(ppProject.GetKey());
            }
            //
            log.Log(Level.SEVERE, "Nothing selected");
            return false;
        }

        /// <summary>
        /// Save to Order
        /// </summary>
        /// <param name="C_Order_ID">id</param>
        /// <returns>true if saved</returns>
        private bool Cmd_SaveOrder(int C_Order_ID)
        {
            
            //System.Threading.ThreadPool.QueueUserWorkItem(delegate
            //{
                log.Config("C_Order_ID=" + C_Order_ID);
                MOrder order = new MOrder(Envs.GetContext(), C_Order_ID, null);
                if (order.Get_ID() == 0)
                {
                    log.Log(Level.SEVERE, "Not found - C_Order_ID=" + C_Order_ID);
                    //               return false;
                }
                int lineCount = 0;
                bool chk = false;
                Decimal qty = 0;
                //	for all bom lines
                if (_selectionList != null)
                {
                    bool isQtySet = false;
                    for (int i = 0; i < _selectionList.Count; i++)
                    {
                        isQtySet = true;
                        Dispatcher.BeginInvoke(delegate
                           {
                               if (IsSelectionSelected(_selectionList[i]))
                               {
                                   chk = true;
                                   qty = (Decimal)((VAdvantage.Controls.VNumTextBox)_qtyList[i]).GetValue();
                               }
                               isQtySet = false;
                               
                           });
                        while (isQtySet)
                        {

                        }
                        if (chk)
                        {
                            int M_Product_ID = Util.GetValueOfInt(_productList[i]);//.intValue();
                            //	Create Line
                            MOrderLine ol = new MOrderLine(order);
                            ol.SetM_Product_ID(M_Product_ID, true);
                            ol.SetQty(qty);
                            ol.SetPrice();
                            ol.SetTax();
                            if (ol.Save())
                            {
                                lineCount++;
                            }
                            else
                            {
                                log.Log(Level.SEVERE, "Line not saved");
                            }
                        }	//	line selected
                    }	//	for all bom lines
                }
                log.Config("#" + lineCount);
            //});
           //SetBusy(false);
            // log.Config("#" + lineCount);
            return true;
        }

        /// <summary>
        /// Save to Invoice
        /// </summary>
        /// <param name="C_Invoice_ID">id</param>
        /// <returns>true if saved</returns>
        private bool Cmd_SaveInvoice(int C_Invoice_ID)
        {
            Decimal qty = 0;
            //SetBusy(true);
            //System.Threading.ThreadPool.QueueUserWorkItem(delegate
            //{
                log.Config("C_Invoice_ID=" + C_Invoice_ID);
                MInvoice invoice = new MInvoice(Envs.GetContext(), C_Invoice_ID, null);
                if (invoice.Get_ID() == 0)
                {
                    log.Log(Level.SEVERE, "Not found - C_Invoice_ID=" + C_Invoice_ID);
                    //                 return false;
                }
                int lineCount = 0;
                bool chk = false;
                //	for all bom lines
                if (_selectionList != null)
                {
                    bool isQtySet = false;
                    for (int i = 0; i < _selectionList.Count; i++)
                    {
                        isQtySet = true;
                        Dispatcher.BeginInvoke(delegate
                           {
                               if (IsSelectionSelected(_selectionList[i]))
                               {
                                   chk = true;
                                   qty = (Decimal)((VAdvantage.Controls.VNumTextBox)_qtyList[i]).GetValue();
                               }
                               isQtySet = false;
                           });
                        while (isQtySet)
                        {

                        }
                        if (chk)
                        {
                            int M_Product_ID = Util.GetValueOfInt(_productList[i]);//.intValue();
                            //	Create Line
                            MInvoiceLine il = new MInvoiceLine(invoice);
                            il.SetM_Product_ID(M_Product_ID, true);
                            il.SetQty(qty);
                            il.SetPrice();
                            il.SetTax();
                            if (il.Save())
                            {
                                lineCount++;
                            }
                            else
                            {
                                log.Log(Level.SEVERE, "Line not saved");
                            }
                        }	//	line selected
                    }	//	for all bom lines

                    log.Config("#" + lineCount);
                }
            //});
            //SetBusy(false);
            
            return true;
        }

        /// <summary>
        /// Save to Project
        /// </summary>
        /// <param name="C_Project_ID">id</param>
        /// <returns>true if saved</returns>
        private bool Cmd_SaveProject(int C_Project_ID)
        {
            Decimal qty = 0;
            //SetBusy(true);
            //System.Threading.ThreadPool.QueueUserWorkItem(delegate
            //{
                log.Config("C_Project_ID=" + C_Project_ID);
                MProject project = new MProject(Envs.GetContext(), C_Project_ID, null);
                if (project.Get_ID() == 0)
                {
                    log.Log(Level.SEVERE, "Not found - C_Project_ID=" + C_Project_ID);
                    //                return false;
                }
                int lineCount = 0;
                bool chk=false;
                //	for all bom lines
                if (_selectionList != null)
                {
                    bool isQtySet = false;
                    for (int i = 0; i < _selectionList.Count; i++)
                    {
                        isQtySet = true;
                        Dispatcher.BeginInvoke(delegate
                            {
                                if (IsSelectionSelected(_selectionList[i]))
                                {
                                    //Decimal qty = Utility.Util.GetValueOfDecimal((VAdvantage.Controls.VNumTextBox)_qtyList[i].GetValue());
                                    chk = true;

                                    qty = Util.GetValueOfDecimal(_qtyList[i].GetValue());

                                }
                                isQtySet = false;
                            });
                        while (isQtySet)
                        {

                        }
                        if (chk)
                        {
                            int M_Product_ID = Util.GetValueOfInt(_productList[i]);//.intValue();
                            //	Create Line
                            MProjectLine pl = new MProjectLine(project);
                            pl.SetM_Product_ID(M_Product_ID);
                            pl.SetPlannedQty(qty);
                            if (pl.Save())
                            {
                                lineCount++;
                            }
                            else
                            {
                                log.Log(Level.SEVERE, "Line not saved");
                            }
                        }	//	line selected
                    }	//	for all bom lines

                    log.Config("#" + lineCount);
                }
            //});
            //SetBusy(true);
            return true;
        }






        void b_Click(object sender, RoutedEventArgs e)
        {
            Cmd_Selection(sender);
            OkCheck();
        }

        void cb_Click(object sender, RoutedEventArgs e)
        {
            Cmd_Selection(sender);
            OkCheck();
        }

        void chkCB_Click(object sender, RoutedEventArgs e)
        {
            Cmd_Selection(sender);
            OkCheck();
        }



        void vcmbProjectField_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            KeyNamePair pp = (KeyNamePair)vcmbProjectField.SelectedItem;
            bool valid = (pp != null && pp.GetKey() > 0);

            if (vcmbOrderField != null)
            {
                //cmbOrderField.setReadWrite(!valid);
                vcmbOrderField.IsEnabled = !valid;
            }
            if (vcmbInvoiceField != null)
            {
                // cmbInvoiceField.setReadWrite(!valid);
                vcmbInvoiceField.IsEnabled = !valid;
            }
            OkCheck();
        }

        void vcmbInvoiceField_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            KeyNamePair pp = (KeyNamePair)vcmbInvoiceField.SelectedItem;
            bool valid = (pp != null && pp.GetKey() > 0);

            if (vcmbOrderField != null)
            {
                //cmbOrderField.setReadWrite(!valid);
                vcmbOrderField.IsEnabled = !valid;
            }
            if (vcmbProjectField != null)
            {
                //cmbProjectField.setReadWrite(!valid);
                vcmbProjectField.IsEnabled = !valid;
            }
            OkCheck();
        }

        void vcmbProductField_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (vcmbProductField.SelectedIndex == 0)
            {
                return;
            }
           SetBusy(true);
           txtBusy.Text = Msg.GetMsg("Processing");
            _qty = Util.GetValueOfDecimal(txtProductQty.Text);
            KeyNamePair pp = (KeyNamePair)vcmbProductField.SelectedItem;
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                _product = MProduct.Get(Envs.GetContext(), pp.GetKey());
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => CallFunctions());
            });
            //CreateMainPanel();

        }


        public void CallFunctions()
        {
            CreateMainPanel();
            SizeIt();
            OkCheck();
        }

        void vcmbOrderField_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            KeyNamePair pp = (KeyNamePair)vcmbOrderField.SelectedItem;
            bool valid = (pp != null && pp.GetKey() > 0);
            if (vcmbInvoiceField != null)
            {
                //cmbInvoiceField.setReadWrite(!valid);
                vcmbInvoiceField.IsEnabled = !valid;
            }
            if (vcmbProjectField != null)
            {
                //cmbProjectField.setReadWrite(!valid);
                vcmbProjectField.IsEnabled = !valid;
            }
            OkCheck();
        }

        private void OkCheck()
        {
            //	Enable OK
            bool OK = _product != null;
            if (OK)
            {
                KeyNamePair pp = null;
                if (vcmbOrderField != null)
                {
                    pp = (KeyNamePair)vcmbOrderField.SelectedItem;
                }
                if ((pp == null || pp.GetKey() <= 0) && vcmbInvoiceField != null)
                {
                    pp = (KeyNamePair)vcmbInvoiceField.SelectedItem;
                }
                if ((pp == null || pp.GetKey() <= 0) && vcmbProjectField != null)
                {
                    pp = (KeyNamePair)vcmbProjectField.SelectedItem;
                }
                OK = (pp != null && pp.GetKey() > 0);
            }
            vbtnOk.IsEnabled = OK;
            //confirmPanel.getOKButton().setEnabled(OK);
        }

        // This event handler is where the actual,
        // potentially time-consuming work is done.
        //private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        //{
        //    e.Result = Cmd_Save();
        //}

        // This event handler deals with the results of the
        // background operation.

        private void backgroundWorker1_RunWorkerCompleted(
            object sender, RunWorkerCompletedEventArgs e)
        {
            //ShowCursor(Cursors.Arrow);
            //tmr.Dispose();
            // obj.Hide();

            //  showProgress = false;
            //  backgroundWorker1.Dispose();
        }

        /// <summary>
        /// function to save client
        /// </summary>
        /// <returns>int primary key</returns>
        private void BackThread()
        {
            //if there is no running process at background 
            if (!backgroundWorker1.IsBusy)
            {
                ShowCursor(Cursors.Wait);
                //obj.WindowState = System.Windows.Forms.FormWindowState.Normal;

                // obj.Show();
                backgroundWorker1.RunWorkerAsync();
                showProgress = true;
                //  tmr.Start();

                // Keep UI messages moving, so the form remains 
                // responsive during the asynchronous operation.
                ////Application.DoEvents();
            }
            //else show message
            else
            {
                ShowMessage.Error("AllreadyRunning", null, "");
            }
        }

        /// <summary>
        /// Intilize BackGroundWorker Thread
        /// </summary>
        private void InitializeBackgoundWorker()
        {
            //backgroundWorker1.DoWork +=
            //    new DoWorkEventHandler(backgroundWorker1_DoWork);
            backgroundWorker1.RunWorkerCompleted +=
                new RunWorkerCompletedEventHandler(
            backgroundWorker1_RunWorkerCompleted);
        }

        /// <summary>
        /// Set The cursors
        /// </summary>
        /// <param name="curType"></param>
        private void ShowCursor(Cursor curType)
        {
            this.Cursor = curType;
        }

        bool showProgress = true;
        //VAdvantage.Framework.Progress obj = new VAdvantage.Framework.Progress();
        // Timer tmr = new Timer();
        BackgroundWorker backgroundWorker1 = new BackgroundWorker();

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tmrInitialTenant_Tick(object sender, EventArgs e)
        {
            if (showProgress == true)
            {
            }
            else
            {
                // tmr.Stop();
                //tmr.Dispose();
            }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void vbtnOk_Click(object sender, RoutedEventArgs e)
        {
             bool chkSave=false;
            KeyNamePair ppOrder = (KeyNamePair)vcmbOrderField.SelectedItem;
            KeyNamePair ppInvoice = (KeyNamePair)vcmbInvoiceField.SelectedItem;
            KeyNamePair ppProject = (KeyNamePair)vcmbProjectField.SelectedItem;
            SetBusy(true);
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                if (Cmd_Save(ppOrder,ppInvoice,ppProject))
                {
                    Dispatcher.BeginInvoke(() => EndProcess());
                }
            });
            //OkCheck();
        }

        private void EndProcess()
        {
            SetBusy(false);
            Dispose();
        }

        private void vbtnCancel_Click(object sender, RoutedEventArgs e)
        {
            Dispose();
        }

        private void busyWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }   
    }
}
